package com.xtaller.sdboot.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.sdboot.utils.helper.ValidatorHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : Taller
 * @date : 2020/3/1 00:07
 * @Description : Token 认证
 */
@Slf4j
@Component
public class TokenFilter extends OriginalFilter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        var accessToken = request.getHeader("token");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        var pm = getByRequest(request);

        if (pm.getIsToken()) {
            // 开始校验Token
            if (ValidatorHelper.isEmpty(accessToken)) {
                response.setStatus(400);
                response.getWriter().write(result(400, "token信息不能为空"));
                return false;
            }
            // 判断token有效性
            Claims claims = getInfoByToken(accessToken);
            if (claims == null) {
                response.setStatus(401);
                response.getWriter().write(result(401, "非法Token信息"));
                return false;
            }
            // 判断token单点操作
            var cacheKey = "account-" + claims.getId();
            // 判断token的一致性
            var cache = cacheUtil.get(cacheKey, JSONObject.class);

            if (cache == null) {
                response.setStatus(401);
                response.getWriter().write(result(401, "请重新登录"));
                return false;
            }
            if (!ValidatorHelper.equals(cache.getString("token"), accessToken)) {
                response.setStatus(401);
                response.getWriter().write(result(401, "当前账户已在别处登录"));
                return false;
            }
        }
        return true;
    }
}
